package com.gmp.material.controller;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.gmp.common.annotation.Log;
import com.gmp.common.core.controller.BaseController;
import com.gmp.common.core.domain.AjaxResult;
import com.gmp.common.enums.BusinessType;
import com.gmp.material.domain.MaterialReceiptRecord;
import com.gmp.material.service.IMaterialReceiptRecordService;
import com.gmp.common.utils.poi.ExcelUtil;
import com.gmp.common.core.page.TableDataInfo;

/**
 * 物料记录管理Controller
 *
 * @author Koi
 * @date 2025-07-26
 */
@RestController
@Api(tags = "物料记录管理")
@RequestMapping("/material/MaterialRecord")
public class MaterialReceiptRecordController extends BaseController {
    @Autowired
    private IMaterialReceiptRecordService materialReceiptRecordService;


    /**
     * 查询物料记录管理列表
     */
    @PreAuthorize("@ss.hasPermi('material:MaterialRecord:list')")
    @GetMapping("/list")
    @ApiOperation("查询物料记录管理列表")
    public TableDataInfo list(MaterialReceiptRecord materialReceiptRecord) {
        startPage();
        //进行了逻辑删除处理
        List<MaterialReceiptRecord> list = materialReceiptRecordService.selectMaterialReceiptRecordList(materialReceiptRecord);
        return getDataTable(list);
    }

    /**
     * 导出物料记录管理列表
     */
    @PreAuthorize("@ss.hasPermi('material:MaterialRecord:export')")
    @Log(title = "物料记录管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    //@ApiOperation("导出物料记录管理列表")
    public void export(HttpServletResponse response, MaterialReceiptRecord materialReceiptRecord) {
        List<MaterialReceiptRecord> list = materialReceiptRecordService.selectMaterialReceiptRecordList(materialReceiptRecord);
        ExcelUtil<MaterialReceiptRecord> util = new ExcelUtil<MaterialReceiptRecord>(MaterialReceiptRecord.class);
        util.exportExcel(response, list, "物料记录管理数据");
    }

    /**
     * 获取物料记录管理详细信息
     */
    @PreAuthorize("@ss.hasPermi('material:MaterialRecord:query')")
    @GetMapping(value = "/{id}")
    @ApiOperation( "根据Id获取物料记录详细信息")
    public AjaxResult getInfo(@PathVariable("id") String id) {
        return success(materialReceiptRecordService.selectMaterialReceiptRecordById(id));
    }

    /**
     * 新增物料记录管理
     */
    @PreAuthorize("@ss.hasPermi('material:MaterialRecord:add')")
    @Log(title = "物料记录管理", businessType = BusinessType.INSERT)
    @ApiOperation("新增物料记录管理")
    @PostMapping
    public AjaxResult add(@RequestBody MaterialReceiptRecord materialReceiptRecord) {

        // 默认设置 收货状态为未检查
        materialReceiptRecord.setReceiptStatus(1);

        // 生成收货编号 (通常是唯一标识符) 使用日期+随机数生成 (更具可读性)
        // 生成收货编号 (日期+2位随机数，更具可读性)
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
        String dateStr = LocalDate.now().format(formatter);
        // 生成2位随机数（00-99）
        String randomNum = String.format("%02d", new Random().nextInt(100));
        String receiptNumber = "REC-" + dateStr + randomNum;
        materialReceiptRecord.setReceiptNumber(receiptNumber);

        // 生成物料编码
        String materialCode = "MAT-" + String.format("%06d", new Random().nextInt(1000000));
        materialReceiptRecord.setMaterialCode(materialCode);

        // 生成收货日期 (通常是当前日期)
        materialReceiptRecord.setReceiptDate(new Date()); // 字段类型是Date

        //生成合格 数量
        // 将字符串转换为数值类型（根据实际情况选择int或double）
        int received = Integer.parseInt(materialReceiptRecord.getReceivedQuantity());
        int rejected = Integer.parseInt(materialReceiptRecord.getRejectedQuantity());
        int qualified = received - rejected;
        materialReceiptRecord.setQualifiedQuantity(String.valueOf(qualified));

        //设置逻辑删除
        materialReceiptRecord.setIsDelete(0);

        return toAjax(materialReceiptRecordService.save(materialReceiptRecord));
    }

    /**
     * 修改物料记录管理
     */
    @PreAuthorize("@ss.hasPermi('material:MaterialRecord:edit')")
    @Log(title = "物料记录管理", businessType = BusinessType.UPDATE)
    @ApiOperation("修改物料记录管理")
    @PutMapping
    public AjaxResult edit(@RequestBody MaterialReceiptRecord materialReceiptRecord) {
        return toAjax(materialReceiptRecordService.updateMaterialReceiptRecord(materialReceiptRecord));
    }

    /**
     * 删除物料记录管理
     */
    @PreAuthorize("@ss.hasPermi('material:MaterialRecord:remove')")
    @Log(title = "物料记录管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    @ApiOperation("删除物料记录管理")
    public AjaxResult remove(@PathVariable String[] ids) {
        return toAjax(materialReceiptRecordService.removeBatchByIds(Arrays.asList(ids)));
    }


    //查看所有物料信息
    @PreAuthorize("@ss.hasPermi('material:MaterialRecord:getAllMaterial')")
    @PostMapping("/getAllMaterial")
    @ApiOperation("查看所有物料信息")
    public AjaxResult getAllMaterial(){
        LambdaQueryWrapper<MaterialReceiptRecord> queryWrapper = new LambdaQueryWrapper<>();
        return success(materialReceiptRecordService.list(queryWrapper));
    }


    //根据物料编码查询物料信息
    @PreAuthorize("@ss.hasPermi('material:MaterialRecord:getMaterialByCode')")
    @GetMapping("/getMaterialByCode/{materialCode}")
    @ApiOperation("根据物料编码查询物料信息")
    public AjaxResult getMaterialByCode(@PathVariable String materialCode){
        // 处理逗号分隔的多个物料编码
        String[] materialCodes = materialCode.split(",");
        // 去除每个编码前后的空格（防止用户输入时带空格）
        List<String> codeList = Arrays.stream(materialCodes)
                .map(String::trim)
                .collect(Collectors.toList());

        LambdaQueryWrapper<MaterialReceiptRecord> queryWrapper = new LambdaQueryWrapper<>();
        // 使用in条件查询所有匹配的编码
        queryWrapper.in(MaterialReceiptRecord::getMaterialCode, codeList);
        return success(materialReceiptRecordService.list(queryWrapper));
    }
}
